<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
	<th:block th:include="include :: header('客户资料新增及修改')" />
	<style type="text/css">
		.layui-elem-quote{padding:8px 15px;line-height:30px}
		.layui-col-md4{width:32%}
		.layui-form-item{margin-bottom:0}
		.getUpload{color: #009688;font-size: 18px;position: absolute;top:5px;right: 9px;}
		.layui-disabled{color: #999 !important}
		.getMore{line-height: initial;position: absolute;top: 10px !important;right: 8px !important;}
	</style>
</head>
<body>
<form class="layui-form" id="form-customer-add" style="padding: 0 0 0 0;">
<input type="hidden" id="guid" name="guid"  th:value="${guid}">
<input type="hidden" name="bShared"  th:value="${customerInfo?.bShared?:0}">
<div class="layui-col-md12" id="top_height">
	<blockquote class="layui-elem-quote"><b>客户基础资料</b></blockquote>
	<div class="layui-form-item">
		<div th:each="field:${gridColumns.dictionaryForPageFieldList}" th:if="${field.fieldFrontTop} eq '1' and !${field.fieldFrontHidden}" th:remove="tag">
			<div th:if="${field.fields} eq 'gClient' and ${customerInfo}" class="layui-inline layui-col-md4">
			  <label class="layui-form-label">客户编号：</label>
			  <div class="layui-input-block">
			    <input type="text" name="gClient" id="gClient"  autocomplete="off" placeholder="请输入" class="layui-input layui-disabled" readonly>
			  </div>
			</div>
			<div th:if="${field.fields} ne 'gClient'" class="layui-inline layui-col-md4">
				<label class="layui-form-label" th:utext="(${field.fieldFrontRequired}?'<font class=\'f_red\'>*</font>':'') +${field.fieldName}+'：'"></label>		
				<div class="layui-input-block">
				  	<input th:if="${field.fieldFrontType} eq 't_text'" type="text" th:id="${field.fields}" th:name="${field.fields}" autocomplete="off" placeholder="请输入" class="layui-input" th:lay-verify="${field.fieldFrontRequired}?'required':''">
				  	<select th:if="${field.fieldFrontType} eq 't_dropdown'" th:id="${field.fields}" th:name="${field.fields}" th:with="vtype=${#strings.substringAfter(#strings.substringAfter(field.fieldSearchType,'_'),'_')}" th:lay-verify="${field.fieldFrontRequired}?'required':''">
				  		<div th:with="type=${@baseinfosimple.getBaseInfoSimpleData(vtype)}" th:remove="tag">
							<option value="">请选择</option>
							<option th:each="dict : ${type}" th:text="${dict.vname}" th:value="${dict.vid}" th:selected="${dict.vid} eq ${customerInfo?.trade}"></option>
				  		</div>
					</select>
					<input th:if="${field.fieldFrontType} eq 't_buttontext'" type="text" class="layui-input buttontext" th:name="${field?.fields}" th:id="${field?.fields}" autocomplete="off" th:lay-verify="${field.fieldFrontRequired}?'required':''" readonly/>
				  		<i th:if="${field.fieldFrontType} eq 't_buttontext'" class="layui-icon layui-icon-more getMore" th:onclick="getMore([[${field?.fields}]],null,[[${field?.fieldName}]],[[${#strings.isEmpty(field.fieldSearchType) ? field.fieldFrontExtend1 : field.fieldSearchType}]],false, [[${type eq 'layer' ? true:false}]]);" th:getType="${field?.fields}"></i>
				</div>
			</div>
		</div>
		<div class="layui-inline layui-col-md4">
		  <label class="layui-form-label">省市区：</label>
		  	<div class="layui-input-block">
		  		<div style="width:49%;display:inline-block">
			  	 	<select id="province" name="province" lay-filter="province" th:with="type=${@baseinfosimple.getBaseInfoSimpleData('area2')}">
						<option></option>
						<option th:each="dict : ${type}" th:text="${dict.vname}" th:data-guid="${dict.guid}" th:value="${dict.vid}" th:selected="${dict.vid} eq ${customerInfo?.province}"></option>
					</select>
				</div>
				<div style="width:49%;display:inline-block">
					<select id="city" name="city" lay-filter="city">
					</select>
				</div>
			</div>
<!-- 			<div class="layui-input-inline" id="areaDiv"> -->
<!-- 				<select id="area" name="area" lay-filter="area" th:with="type=${@baseinfosimple.getBaseInfoSimpleData('area4')}"> -->
<!-- 					<option value="">请选择</option> -->
<!-- 					<option th:each="dict : ${type}" th:text="${dict.vname}" th:data-guid="${dict.guid}" th:value="${dict.vid}" th:selected="${dict.vid} eq ${customerInfo?.area}"></option> -->
<!-- 				</select> -->
<!-- 		  	</div> -->
		</div>
		<div th:if="${customerInfo}" class="layui-inline layui-col-md4">
		  <label class="layui-form-label">附件：</label>
		  <div class="layui-input-block">
		    <input type="text" id="vCustomerFiles" th:value="${customerInfo?.vCustomerFiles}" autocomplete="off" class="layui-input" readonly>
		    <i class="layui-icon layui-icon-upload getUpload" onclick="uploadFile();" gettype="vCustomerFiles"></i>
		  </div>
		</div>
	</div>
	<blockquote class="layui-elem-quote"><b>客户财务资料</b></blockquote>
	<div class="layui-form-item">
		<div th:each="field:${gridColumns.dictionaryForPageFieldList}" th:if="${field.fieldFrontTop} eq '5' and !${field.fieldFrontHidden}" class="layui-inline layui-col-md4">
			<label class="layui-form-label" th:utext="(${field.fieldFrontRequired}?'<font class=\'f_red\'>*</font>':'') +${field.fieldName}+'：'"></label>		
			<div class="layui-input-block">
			  	<input th:if="${field.fieldFrontType} eq 't_text'" type="text" th:id="${field.fields}" th:name="${field.fields}" autocomplete="off" placeholder="请输入" class="layui-input" th:lay-verify="${field.fieldFrontRequired}?'required':''">
			  	<select th:if="${field.fieldFrontType} eq 't_dropdown'" th:id="${field.fields}" th:name="${field.fields}" th:with="vtype=${#strings.substringAfter(#strings.substringAfter(field.fieldSearchType,'_'),'_')}" th:lay-verify="${field.fieldFrontRequired}?'required':''">
			  		<div th:with="type=${@baseinfosimple.getBaseInfoSimpleData(vtype)}" th:remove="tag">
						<option value="">请选择</option>
						<option th:each="dict : ${type}" th:text="${dict.vname}" th:value="${dict.vid}" th:selected="${dict.vid} eq ${customerInfo?.trade}"></option>
			  		</div>
			</select>
			</div>
		</div>
	</div>
</div>
<div class="layui-col-md12">
	<blockquote class="layui-elem-quote"><b>客户联系人</b>
	<div th:if="!${canntEdit}" class="layui-btn layui-btn-normal layui-table-tools" onClick="addRow()" style="float:right">
		<p class="dhicon dh-plus" style="color:white;font-size:14px"><span class="fa_span">新增</span></p>
	</div>
	</blockquote>
	<div class="mid-content">
	    <table class="layui-hide" id="dhtable" lay-filter="ftable"></table>
	</div>
</div>
<div class="layui-col-md12">
	<div class="layui-btn-container" style="float: right;margin: 10px;">
		<input th:if="!${canntEdit}" class="layui-btn layui-table-tools" type="button" lay-submit="" lay-filter="btn_save" value="保存">
        <input th:if="${customerInfo==null}" class="layui-btn layui-btn-normal layui-table-tools" type="button" lay-submit="" lay-filter="btn_savenew" value="保存并新建" id="saveNew">
		<input class="layui-btn layui-btn-primary layui-table-tools" type="button" onclick="closeTab()" value="关闭">
    </div>
</div>
</form>
<th:block th:include="include :: footer" />
<script type="text/html" id="barDh">
    <a th:class="${canntEdit}?'layui-btn layui-btn-xs dhicon dh-remove layui-btn-disabled':'layui-btn layui-btn-danger layui-btn-xs dhicon dh-remove'" th:lay-event="${canntEdit}?'':'del'">&nbsp;删除</a>
</script>
<script type="text/html" id="bfkH">
    <input type="radio" name="bfk" {{ d.bfk == 1 ? 'checked' : '' }} th:disabled="${canntEdit}">      
</script>
<script type="text/html" id="blxrH">
    <input type="radio" name="blxr" {{ d.blxr == 1 ? 'checked' : '' }} th:disabled="${canntEdit}">      
</script>
<script type="text/html" id="bshH">
    <input type="radio" name="bsh" {{ d.bsh == 1 ? 'checked' : '' }} th:disabled="${canntEdit}">        
</script>
<script type="text/html" id="bspH">
    <input type="radio" name="bsp" {{ d.bsp == 1 ? 'checked' : '' }} th:disabled="${canntEdit}">
</script>
<script th:inline="javascript">
	/*<![CDATA[*/
	var prefix1 = ctx + "crm/customer";
	var prefix2 = ctx + "crm/customerpersion", cCityName = [[${customerInfo?.city}]];
	var canntEdit=[[${canntEdit}]],//是否不可编辑（仅适用于他人查看详情）
		gridColumns=[[${gridColumns}]],
		moduleTable=[[${moduleTable}]],
		customerInfo=[[${customerInfo}]];
	/*]]>*/
</script>
<script type="text/javascript">
var $,layer,form,table,gClient;
layui.use(['table','form','layer','jquery'], function () {
    $ = layui.$,layer = layui.layer,form = layui.form,table = layui.table;
    var tableBody=[[
   	 	{type:'numbers',rowspan: 2},
        {field: 'vName',title: "<font class='f_red'>*</font>姓名",rowspan: 2,edit:'text'},
       	{field: 'vTel',title: "<font class='f_red'>*</font>电话",rowspan: 2,edit:'text'},
       	{field: 'vwxh',title: '微信号',rowspan: 2,edit:'text'},
       	{field: 'vQQ',title: 'QQ',rowspan: 2,edit:'text'},
       	{field: 'vAddress',title: "<font class='f_red'>*</font>地址",rowspan: 2,edit:'text'},
        {field: 'vFax',title: '传真',rowspan: 2,edit:'text'},
        {field: 'vMail',title: '邮箱',rowspan: 2,edit:'text'},
        {align: 'center',title: '默认设置',colspan:4},
        {title: '操作',align: 'center',templet:'#barDh',rowspan: 2}
    ], [
        {field: 'bfk', title: '付款人',width:75,align: 'center',event: 'check',templet:'#bfkH'},
        {field: 'blxr', title: '联系人',width:75,align: 'center',event: 'check',templet:'#blxrH'},
        {field: 'bsh', title: '收货人',width:75,align: 'center',event: 'check',templet:'#bshH'},
        {field: 'bsp', title: '收票人',width:75,align: 'center',event: 'check',templet:'#bspH'}
    ]
    ];
    if(customerInfo){//存在customerInfo对象，即编辑页面，赋值
    	$.each(customerInfo,function(i,v){
    		$('#'+i).val(v);
    	})
    	if(canntEdit){
    		$.each(tableBody[0],function(i,v){delete v['edit']})//移除表格编辑属性
    		$('input').attr('readonly','readonly');
    		$('#top_height input').addClass('layui-disabled');
    		$('select').attr('disabled','disabled');
    	}
    	form.render('select');
    }
	$('#gClient').val()==''? gClient=null:gClient=$('#gClient').val();//通过gclient判断新增还是修改，来改变下面加载的表格
	if(gClient){
		$('#saveNew').hide();//控制保存并新建按钮
	}
  	$.ajax({
		url: prefix2 + '/list?gClient='+gClient,
        type: "get",
        dataType: "json",
        success: function(result) {
        	$.tablelist.init({
				elem: '#dhtable'
				,modalName: "客户联系人"
				,data: result.data
				,page:false
				,limit:100
				,createUrl: prefix2 + "/add?{id}"
				,updateUrl: prefix2 + "/edit?gClient={id}"
				,cols: tableBody
				,defaultToolbar:[]
				,height:'full-'+($('#top_height').height()+100)
            });
        }
  	});
	//监听工具条
	table.on('tool(ftable)', function (obj) {
		var data = obj.data, event = obj.event, tr = obj.tr,iName; //获得当前行 tr 的DOM对象;
		iName=this.getAttribute("data-field");
		switch(event){
			case "check":
				$.each(table.cache.dhtable,function(i,v){
					if(v.LAY_TABLE_INDEX==($("tr").index(obj.tr)-2)){//缓存表内的下标和当前事件行下标的判断
						if(tr.find("input[name='"+iName+"']").prop('checked')){
							v[iName]=1;
						}
					}else{
						v[iName]=0;
					}
	        	});
				break;
			case "del":
				if(data.bfk||data.blxr||data.bsh||data.bsp){
					layer.msg("不能删除有默认设置的联系人，请重新操作！",{icon:2});
				}else{
					layer.confirm(data.guid?"该联系人删除将无法恢复，是否确定删除？":"是否删除这条新增联系人？",
						{icon: 3,offset: '10%',title: "系统提示",btn: ['确认', '取消'],yes: function(index){
							if(data.guid)$.operate.post(prefix2 + "/delete/", {'customerPersionInfoItems':JSON.stringify([{'guid':data.guid}])});
							layer.close(index);
							obj.del();//删除对应行（tr）的DOM结构，并更新缓存（变为空数组）
							var listData=table.cache.dhtable;
							for(var i=0; i < listData.length; i++)if(!listData[i] || listData[i].length==0)listData.splice(i, 1);//删除一项
							table.reload('dhtable',{data : listData});
						},btn2: function(){
	        				layer.closeAll();
	        			}
					});
				}
				break;
		}
	});
  	//联动获取城市列表
	form.on('select(province)', function(data){
		$("#city").empty();
		$("#area").empty();
		getCityAndArea(data.elem[data.elem.selectedIndex].dataset.guid,'');
	}); 
	form.on('select(city)', function(data){
		$("#area").empty();
		getCityAndArea('',data.elem[data.elem.selectedIndex].dataset.guid);
	}); 
	function getCityAndArea(value1,value2){
		if(value1){
			$.ajax({
				url: '/base/baseinfo/list?pguid='+value1,
		        type: 'get',
		        dataType: 'json',
				success: function(result) {
					$('#city').append(new Option('请选择城市',''));
					$.each(result.data,function(i,v){
						$('#city').append('<option value="'+v.vid+'" data-guid="'+v.guid+'">'+v.vname+'</option>')
		        	});
					form.render();
				}
			});
		}
		if(value2){
			$.ajax({
				url: '/base/baseinfo/list?pguid='+value2,
		        type: 'get',
		        dataType: 'json',
				success: function(result) {
					$('#area').append(new Option('请选择区县',''));
					$.each(result.data,function(k,v){
						$('#area').append(new Option(v.vname,v.vid));
		        	});
					form.render();
				}
			});
		}
	};
	$(function(){
		var cProvince = $("[name=province]").find("option:selected").attr("data-guid");
		if(cProvince){
			$.ajax({
				url: '/base/baseinfo/list?pguid='+cProvince,
		        type: 'get',
		        dataType: 'json',
				success: function(result) {
					$('#city').append(new Option('请选择城市',''));
					$.each(result.data,function(i,v){
						if(v.vname == cCityName){
							$('#city').append('<option value="'+v.vid+'" data-guid="'+v.guid+'" selected>'+v.vname+'</option>')
						}else{
							$('#city').append('<option value="'+v.vid+'" data-guid="'+v.guid+'">'+v.vname+'</option>')
						}
		        	});
					form.render();
				}
			});
		}
	})
	form.on('submit(btn_save)', function(data){
		submitHandler();
	}); 
	form.on('submit(btn_savenew)', function(data){
		submitHandler(true);
	});
});
function addRow(){//添加一行联系人
	var listData = table.cache.dhtable;
	if(listData.length==0)listData.push({"bfk":1,"blxr":1,"bsh":1,"bsp":1,"newData":1});
	else listData.push({"bfk":0,"blxr":0,"bsh":0,"bsp":0,"newData":1});
	table.reload('dhtable',{data : listData});
}
function closeTab(){
	top.layui.admin.closeThisTabs();
}
//保存调用的方法
function submitHandler(saveNew=false) {
	var errorFlag = false;
    if(table.cache.dhtable.length!=0){
    	$.each(table.cache.dhtable,function(i,v){
	       	if(!v["vName"] || !v["vTel"] || !v["vAddress"]){
	       		layer.msg('第'+(i+1)+'行联系人的姓名、电话、地址为必填，请检查！', {icon: 2});
	       		errorFlag = true;
	       		return false;
	       	}
    	});
    	if(errorFlag)return false;//退出保存
		if($("#gClient").val()){//修改客户
			$.each(table.cache.dhtable,function(i,v){
				if(v["newData"]==1)v["guid"]=$("#guid").val();//如果是新增联系人，则带上客户资料的guid，新增查询gclient
			})
			$.operate.post(prefix1 + "/editpost",{'customerInfoItems':JSON.stringify([$.common.formToJSON('form-customer-add')])},function(res){//修改客户
				if(res.code==0)$.operate.post(prefix2 + "/editpost", {'customerPersionInfoItems':JSON.stringify(table.cache.dhtable, null, 2)});//覆盖联系人
				else $.operate.ajaxSuccess(res);
			});
		}else{//新增客户
			$.each(table.cache.dhtable,function(i,v){
				v["guid"]=$("#guid").val();//通过客户guid查询gclient
			})
			$.operate.post(prefix1 + "/addpost", {'customerInfoItems':JSON.stringify([$.common.formToJSON('form-customer-add')])},function(res){//新增客户
				if(res.code==0){
					$.operate.post(prefix2 + "/addpost", {'customerPersionInfoItems':JSON.stringify(table.cache.dhtable, null, 2)},function(res2){//新增联系人
						if(res2.code==0){
							if(saveNew)setTimeout(function(){window.location.reload();}, 2000);
							else{
								var tabTitleObj = $('.layui-tab-title', parent.document).find('.layui-this').find('span');//当前tab对象
								var tabName = tabTitleObj.html();
								tabName = tabName.replace(' - 新增','('+res.data.gClient+') - 修改');
								tabTitleObj.html(tabName);
								window.location.href = prefix1+'/edit?gClient='+res.data.gClient;
							}
						}
					});
				}else $.operate.ajaxSuccess(res);
			});
		}
    }else layer.msg('请添加至少一名联系人！', {icon: 2});
}
function uploadFile(){
	getUploadCommon("vCustomerFiles", "Head", gClient);
}
</script>
</body>
</html>